import { createApp } from "vue";
import axios from "axios";

// 配置服务器地址
const baseURL = process.env.VUE_APP_API_BASE_URL;
let config = {
  baseURL: baseURL || "",
  timeout: 60 * 1000, // Timeout
  withCredentials: true, // Check cross - site Access - Control
};

const _axios = axios.create(config);

// 添加请求拦截器
_axios.interceptors.request.use(
  function (config) {
    console.log("config.headers.Authorization", config.headers.Authorization);
    const token = localStorage.getItem("token");
    config.headers.Authorization = `Bearer ${token}`;
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
_axios.interceptors.response.use(
  function (response) {
    const { authorization } = response.headers;
    console.log("响应拦截-authorization", authorization);
    authorization && localStorage.setItem("token", authorization);
    return response;
  },
  function (error) {
    if (error.response) {
      const status = error.response.status;
      const message = error.response.data.message || "An error occurred";
      if (status === 401) {
        localStorage.removeItem("token");
        window.location.href = "#/login";
      } else if (status === 403) {
        console.error("Forbidden:", message);
      } else if (status >= 400 && status < 500) {
        console.error("客户端错误:", message);
      } else if (status >= 500) {
        console.error("服务器错误:", message);
      }
    } else if (error.request) {
      console.error("No response:", error.request);
    } else {
      console.error("Error:", error.message);
    }
    return Promise.reject(error);
  }
);

const axiosPlugin = {
  install(app) {
    app.config.globalProperties.axios = _axios;
    app.config.globalProperties.$axios = _axios;
    app.provide("axios", _axios);
  },
};

export default axiosPlugin;
